/* Copyright © 2010 LPRM
Universidade Federal do Espírito Santo - RNP-GT CWTools

This file is part of JoinUs!.

JoinUs! is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

JoinUs! is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with JoinUs!. If not, see <http://www.gnu.org/licenses/>. */
package com.isisufes.joinus.appserver;

import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Message extends Servlet1
{
    /**
	 * 
	 */
	private static final long serialVersionUID = -7475494663322024716L;

	@SuppressWarnings("unused")
	private static String[] cfields = { "sender", "message", "read" };

    private PreparedStatement ps_get, ps_set, ps_all, ps_msg, ps_gps_update;

    protected void initStmt()
    {
        ps_get = DBConn.stmt("select * from Message where receiver=? and read=0");
        ps_set = DBConn.stmt("update Message set read=1 where receiver=?");
        ps_all = DBConn.stmt("select * from Message where receiver=?");
        ps_msg = DBConn.stmt("insert into Message(sender,receiver,message) values(?,?,?)");
        ps_gps_update = DBConn.stmt("UPDATE Profile SET gpslat=?, gpslng=?, gpslastupdate=LOCALTIMESTAMP WHERE idprofile=?");
    }

    private String strMessage(ResultSet rs) throws Exception
    {
        StringBuilder sb = new StringBuilder();

        sb.append("<Messages>\n");
        while (rs.next()) {
            sb.append("<Message>\n");
            sb.append("<sender>" + rs.getString("sender") + "</sender>\n");
            sb.append("<message>" + rs.getString("message") + "</message>\n");
            sb.append("<read>" + rs.getString("read") + "</read>\n");
            sb.append("</Message>\n");
        }
        sb.append("</Messages>\n");

        rs.close();
        return sb.toString();
    }

    private void upd() throws Exception
    {
        ps_set.clearParameters();
        ps_set.setInt(1, Integer.parseInt(id));  //
        ps_set.executeUpdate();
    }
    
    private String get() throws Exception
    {
    	//Atualiza a posição do usuário, quando requisitado
    	String updatePos = arg("updatePos");
        if(updatePos.equals("true")){
        	ps_gps_update.setDouble(1, Double.parseDouble(arg("lat")));
        	ps_gps_update.setDouble(2, Double.parseDouble(arg("lng")));
        	ps_gps_update.setInt(3, Integer.parseInt(id));
        	ps_gps_update.executeUpdate();
        }
        
        ps_get.clearParameters();
        ps_get.setInt(1, Integer.parseInt(id));  //
        String ret = strMessage(ps_get.executeQuery());
        upd();

        return ret;
    }

    private String getAll() throws Exception
    {
        ps_all.clearParameters();
        ps_all.setInt(1, Integer.parseInt(id));

        return strMessage(ps_all.executeQuery());
    }

    private String send(String dst, String msg) throws Exception
    {
        ps_msg.clearParameters();
        ps_msg.setInt(1, Integer.parseInt(id));  //
        ps_msg.setInt(2, Integer.parseInt(dst));  // .setString(2, dst);
        ps_msg.setString(3, msg);
        ps_msg.executeUpdate();

        return "";
    }

    protected String dispatch(String action) throws Exception
    {
        String ret = "";//= null;

        if (action.equals("get")) ret = get();
        if (action.equals("getAll")) ret = getAll();
        if (action.equals("send")) ret = send(arg("id"), arg("msg"));

        return ret;
    }
}
